package com.sillyhat.project.common.utils;

import com.sillyhat.project.learning.youdao.dto.YouDaoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * YouDaoHttpUtils
 *
 * @author 徐士宽
 * @date 2017/4/6 16:11
 */
public class YouDaoHttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(YouDaoHttpUtils.class);

//    @Value("${youdao.interfact.value}")
//    private static String youdaoInterface;

    public static YouDaoDTO requestHttpGetToYouDao(String youdaoInterface,String word) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(youdaoInterface + word);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                logger.info(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            InputStream inputStream = connection.getInputStream();
            in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            //有道接口中us-phonetic无法直接转换成实体类中的字段，转java格式后再转
            result = result.replaceAll("us-phonetic","usPhonetic").replaceAll("uk-phonetic","ukPhonetic");
            logger.info(result);
        } catch (Exception e) {
            logger.error("发送GET请求出现异常！",e);
            e.printStackTrace();
        }finally {
            //关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                logger.error("关闭流出现异常",e);
            }
        }
        return JsonUtils.jsonToObject(result,YouDaoDTO.class);
    }

    public static Map<String,Object> requestHttpGetToYouDaoReturnMap(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                logger.info(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            InputStream inputStream = connection.getInputStream();
            in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            result = result.replaceAll("us-phonetic","usPhonetic").replaceAll("uk-phonetic","ukPhonetic");
            logger.info(result);
        } catch (Exception e) {
            logger.error("发送GET请求出现异常！",e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return JsonUtils.jsonToObject(result,Map.class);
    }
}
